<template>
  <div class="base-container">
    <t-form ref="form" :data="queryParams" label-width="80"
            @submit="()=>{this.pagination.current=1;this.queryParams.pageNum=1;this.getList()}"
            @reset="()=>{this.pagination.current=1;this.queryParams.pageNum=1;this.getList()}">
      <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="奖励名称" name="name">
            <t-input
              v-model="queryParams.name"
              clearable
              placeholder="请输入奖励名称"
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="奖励种类" name="awardsType">
            <t-select  style="width: 240px" clearable v-model="queryParams.awardsType"
                       :options="dict.type.awards_type">
            </t-select>
          </t-form-item>
          <t-form-item label="奖项级别" name="awardsLevel">
            <t-select  style="width: 240px" clearable v-model="queryParams.awardsLevel"
                       :options="dict.type.awards_level">
            </t-select>
          </t-form-item>
          <t-form-item label="奖项等级" name="awardsGrade">
            <t-select  style="width: 240px" clearable v-model="queryParams.awardsGrade"
                       :options="dict.type.awards_grade">
            </t-select>
          </t-form-item>
          <t-form-item label="获奖时间" name="awardsDateRange">
            <t-date-range-picker style="width: 280px" :placeholder="['开始时间','结束时间']" v-model="queryParams.awardsDateRange"  allow-input clearable/>
          </t-form-item>
          <t-form-item label="颁奖单位" name="publishDept">
            <t-input
              v-model="queryParams.publishDept"
              clearable
              placeholder="请输入颁奖单位"
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="填报单位" name="declareDeptName">
            <t-input
              v-model="queryParams.declareDeptName"
              clearable
              placeholder="请输入填报单位"
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="参与人员" name="peopleName">
            <t-input
              v-model="queryParams.peopleName"
              clearable
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="奖励状态" name="awardsStatus">
            <t-select  style="width: 240px" clearable v-model="queryParams.awardsStatus"
                       :options="dict.type.achievement_status">
            </t-select>
          </t-form-item>
          <t-form-item label="子系统名称" name="serviceCode">
            <t-select clearable v-model="queryParams.serviceCode" :keys="{label:'serviceName',value:'serviceCode'}"
                      style="width: 240px" :options="serviceOptions"></t-select>
          </t-form-item>
          <t-form-item label="项目名称" name="businessId">
            <t-select
              :disabled="queryParams.serviceCode===''"
              @search="remoteProject"
              placeholder="请先选择子系统后搜索"
              v-model="queryParams.businessId" style="width: 240px" filterable clearable
              :keys="{label:'businessName',value:'businessId'}" :options="projectOptions">
            </t-select>
          </t-form-item>
          <t-form-item label="外部项目名称" name="businessName">
            <t-input
              v-model="queryParams.businessName"
              clearable
              style="width: 240px"
            />
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit">查询</t-button>
          <t-button theme="default" variant="outline" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="btn-group-inline">
      <t-button @click="apply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon" />
        录入
      </t-button>
      <t-button @click="exportExcel" variant="outline" theme="primary">
        <t-icon name="download" slot="icon"/>
        导出
      </t-button>
    </div>
    <t-table
      rowKey="id"
      :data="data"
      :columns="columns"
      hover
      :pagination="pagination"
      :loading="dataLoading"
    >
      <template #name="{row}">
        <t-link @click="dialog.objId=row.id;dialog.header=row.name;dialog.open_review=true" hover="color" theme="primary">{{row.name}}</t-link>
      </template>
      <template #awardsMemberList="{ row }">
        <template v-for="(item,index) in row.awardsMemberList">
          {{item.name}}{{index+1===row.awardsMemberList.length?'':'、'}}
        </template>
      </template>
      <template #awardsProjectList="{ row }">
        <template v-for="(item,index) in row.awardsProjectList">
          {{item.businessName}}{{index+1===row.awardsProjectList.length?'':'、'}}
        </template>
      </template>
      <template #awardsType="{ row }">
        {{ row.awardsType | filterByDict(dict.type.awards_type) }}
      </template>
      <template #awardsLevel="{ row }">
        {{ row.awardsLevel | filterByDict(dict.type.awards_level) }}
      </template>
      <template #awardsGrade="{ row }">
        {{ row.awardsGrade | filterByDict(dict.type.awards_grade) }}
      </template>
      <template #awardsStatus="{ row }">
        <t-tag @click="dialog.header=row.name;dialog.objId=row.id;dialog.open_approve_list=true" class="cursor-pointer"
               :theme="handleTheme(row.awardsStatus, dict.type.achievement_status)" variant="light">
          {{ row.awardsStatus | filterByDict(dict.type.achievement_status) }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-button   @click="updateData(row)" size="small" variant="text"
                   class="t-button-link">
          <t-icon name="edit-1" slot="icon"/>
          编辑
        </t-button>
        <t-button size="small"
                  @click="dialog.objId=row.id;dialog.header=row.name;dialog.open_detail=true"
                  variant="text" class="t-button-link">
          <t-icon name="info-circle" slot="icon"/>
          详情
        </t-button>
        <t-button
          theme="danger"
          @click="delObj(row)"
          size="small"
          variant="text" class="t-button-link">
          <t-icon name="delete" slot="icon"/>
          删除
        </t-button>
      </template>
    </t-table>
    <awards-detail-dialog :objId="dialog.objId" :header="dialog.header" :visible.sync="dialog.open_detail" v-if="dialog.open_detail">
    </awards-detail-dialog>
    <file-review :header="dialog.header" achievementType="5" :visible.sync="dialog.open_review" v-if="dialog.open_review" :objId="dialog.objId"></file-review>
  </div>
</template>

<script>
import awardsDetailDialog from "./components/awards-detail-dialog.vue";
import fileReview from "../components/file-review.vue";

export default {
  name: "awards-index",
  dicts: ['awards_level', 'awards_grade', 'achievement_status','awards_type'],
  components: {
    awardsDetailDialog,
    fileReview
  },
  data() {
    return {
      dialog: {
        header: "",
        open: false,
        objId: null,
        open_approve_list: false,
        open_detail: false,
        open_review: false,
      },
      serviceOptions: [],
      projectOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        awardsLevel: '',
        awardsGrade: '',
        awardsDate: '',
        publishDept: '',
        startAwardsDate: '',
        endAwardsDate: '',
        awardsDateRange: [],
        declareDeptName: '',
        awardsStatus: '',
        peopleName: '',
        businessName: '',
        status: "",
        dateRange: [],
        serviceCode: '',
        businessId: null,
        awardsType: '',
      },
      data: [],
      columns: [
        {
          colKey: "name",
          title: "奖励名称",
          align: "center"
        },
        {
          colKey: "awardsProjectList",
          title: "获奖项目",
          align: "center"
        },
        {
          colKey: "awardsType",
          title: "奖励种类",
          align: "center"
        },
        {
          colKey: "awardsLevel",
          title: "奖项级别",
          align: "center"
        },
        {
          colKey: "awardsGrade",
          title: "获奖等级",
          align: "center"
        },
        {
          colKey: "awardsDate",
          title: "获奖时间",
          align: "center"
        },
        {
          colKey: "publishDept",
          title: "颁奖单位",
          align: "center"
        },
        // {
        //   colKey: "declareDeptName",
        //   title: "填报单位",
        //   align: "center"
        // },
        {
          colKey: "awardsMemberList",
          title: "参与人员",
          align: "center"
        },

        // {
        //   colKey: "createTime",
        //   title: "创建时间",
        //   align: "center"
        // },
        {
          colKey: "awardsStatus",
          title: "奖励状态",
          align: "center",
          fixed: 'right'
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 140,
        }
      ],
      dataLoading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination, pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
    };
  },
  created() {
    Object.assign(this.queryParams, this.handelQuery(this.queryParams, this.$route.query))
    if(this.queryParams.businessId){
      this.remoteProject(this.queryParams.projectName)
    }
    this.getSysServices();
    this.getList();
  },
  methods: {
    updateData(row) {
      sessionStorage.removeItem(`${row.id}-awards-activeForm`)
      const taskId = row.id;
      const activeFormList = [];
      this.$api.cgzh.awards.getAll(row.id).then(response => {
        sessionStorage.removeItem(`${taskId}-awards-awardsId`);
        if(response.data.id){
          sessionStorage.setItem(`${taskId}-awards-awardsId`, response.data.id)
        }else {
          activeFormList.push(0);
        }
        if(response.data.awardsMemberList && response.data.awardsMemberList.length>0){
          sessionStorage.setItem(`${taskId}-awards-memberId`, response.data.awardsMemberList.length)
        }else {
          activeFormList.push(1);
        }
        if(response.data.awardsProjectList && response.data.awardsProjectList.length>0){
          sessionStorage.setItem(`${taskId}-awards-projectId`, response.data.awardsProjectList.length)
        }else {
          activeFormList.push(2);
        }
        if (activeFormList.length <= 0) {
          sessionStorage.setItem(`${taskId}-awards-activeForm`, 3); // 跳转到最后一步
        } else {
          sessionStorage.setItem(`${taskId}-awards-activeForm`, activeFormList[0]); // 跳转到第一个不满足
        }
        this.$router.push({path:`/cgzh/other/awards/awards-apply/${row.id}`,query:{title:`奖励录入-${row.name}`}});
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    apply() {
      this.$router.push(`/cgzh/other/awards/awards-apply/${Date.parse(new Date())}`);
    },
    exportExcel(){
      this.$download(`cgzh/awards/exportAllList`,this.queryParams, `获奖列表_${new Date().getTime()}.xls`)
    },
    remoteProject(search){
      this.$api.cgzh.getProjectByServiceCode({
        serviceCode:this.queryParams.serviceCode,
        // businessId: this.queryParams.businessId,
        projectName:search,
      }).then(response => {
        response.data.forEach(val2 => {
          const index = this.projectOptions.findIndex(val => val.businessId === val2.businessId)
          if (index === -1) {
            this.projectOptions.push(val2);
          }
        })
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getSysServices() {
      this.$api.cgzh.getSysServices().then(response => {
        this.serviceOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getList() {
      this.dataLoading = true;
      [this.queryParams.startAwardsDate,this.queryParams.endAwardsDate] = this.queryParams.awardsDateRange;
      this.$api.cgzh.awards.list(this.queryParams).then(response => {
        this.data = response.rows;
        this.pagination.total = response.total;
        this.dataLoading = false;
      }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    delObj(row) {
      const confirmDia = this.$dialog.confirm({
        header: "系统提示",
        body: `是否确认删除奖励名称为"${row.name}"的数据项？`,
        theme: "warning",
        onConfirm: ({e}) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          this.$api.cgzh.awards.delete(row.id).then(
            (res) => {
              this.getList();
              this.$message.success("删除成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        }
      });
    }
  }
};
</script>

<style scoped>

</style>
